<template>
  <div class="dashboard-editor-container">
      <el-row :gutter="32" style="padding:16px 16px 0;margin-bottom:32px;">
        <el-card>
        <div slot="header" class="clearfix">
          <span>仓库出入库对账界面</span>
          <el-button style="float: right;" type="primary" @click="syncReconciliationData">数据同步</el-button>
        </div>
        <el-table
          v-loading="loading"
          :data="parentReconciliationData"
          row-key="serialNum"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column label="出/入库单编号" width="200" prop="storageId">
          <template slot-scope="scope">
          <el-button type="text" @click="showChildDialog(scope.row)">{{ scope.row.storageId }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="采购单号" width="140" prop="purcOrderCode" />
          <el-table-column label="出/入库日期" width="180" prop="storageTime">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.storageTime) }}
              </template>
          </el-table-column>
          <el-table-column label="条件" width="140" align="center" prop="recoCondition" />
          <el-table-column label="出/入库类型" width="120" align="center" prop="recptType" />
          <el-table-column label="出/入库数量" width="120" align="center" prop="storageNum" />
          <el-table-column label="仓管确认" width="120" align="center" prop="storekeeperConfirm" />
          <el-table-column label="审核人" width="120" align="center" prop="auditName" />
            <el-table-column label="审核状态" width="120" align="center" prop="auditStatus">
                       <template slot-scope="scope">
                         <span v-if="scope.row.auditStatus === '1'">已审核</span>
                         <span v-else>
                           <el-button
                            v-if="scope.row.auditStatus !== '1'"
                            size="mini"
                            type="text"
                            @click="auditReconciliationUpdate(scope.row)"
                          >
                            审核
                          </el-button>
                          </span>
                       </template>
                     </el-table-column>
          <el-table-column label="审核时间" width="180" align="center" prop="auditDate">
              <template slot-scope="scope">
                  {{ formatDateTime(scope.row.auditDate) }}
              </template>
          </el-table-column>

            <el-table-column label="操作" width="120" align="center">
                        <template slot-scope="scope">

                          <el-button
                            v-if="scope.row.auditStatus === '1'"
                            size="mini"
                            type="text"
                            @click="showChildDialog(scope.row)"
                            :disabled="scope.row.recoStatus === '1'"
                            :class="{'disabled-button': scope.row.recoStatus === '1'}"
                          >
                            {{ scope.row.recoStatus === '1' ? '已完成' : '未对账' }}
                          </el-button>
                        </template>
                      </el-table-column>
        </el-table>
         <el-pagination
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  :page-size="pageSize"
                  :current-page="pageNum"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
      </el-card>
    </el-row>

    <!-- 子节点对话框 -->
    <el-dialog
      title="子节点对账数据"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleClose"
    >
      <el-table
        v-loading="childLoading"
        :data="childReconciliationList"
        row-key="serialNum"
      >
        <el-table-column label="出/入库单编号" width="200" prop="storageId">
        </el-table-column>
        <el-table-column label="采购单号" width="140" prop="purcOrderCode" />
        <el-table-column label="出/入库日期" width="180" prop="storageTime">
            <template slot-scope="scope">
                {{ formatDateTime(scope.row.storageTime) }}
            </template>
        </el-table-column>
        <el-table-column label="条件" width="140" align="center" prop="recoCondition" />
        <el-table-column label="出/入库类型" width="120" align="center" prop="recptType" />
        <el-table-column label="仓库名称" width="120" align="center" prop="invenStoreName" />
        <el-table-column label="物料名称" width="120" align="center" prop="itemName" />
        <el-table-column label="物料编码" width="120" align="center" prop="itemCode" />
        <el-table-column label="出/入库数量" width="120" align="center" prop="storageNum" />
        <el-table-column label="单价" width="120" align="center" prop="unitPrice" />
        <el-table-column label="单位" width="80" align="center" prop="unit" />
        <el-table-column label="规格" width="120" align="center" prop="itemSpec" />
        <el-table-column label="入库金额" width="120" align="center" prop="inAmount" />
        <el-table-column label="出库金额" width="120" align="center" prop="outAmount" />
        <el-table-column label="仓管确认" width="120" align="center" prop="storekeeperConfirm" />
        <el-table-column label="审核人" width="120" align="center" prop="auditName" />
        <el-table-column label="审核状态" width="120" align="center" prop="auditStatus">
                   <template slot-scope="scope">
                     <span v-if="scope.row.auditStatus === '1'">已审核</span>
                     <span v-else>未审核</span>
                   </template>
                 </el-table-column>
        <el-table-column label="审核时间" width="180" align="center" prop="auditDate">
            <template slot-scope="scope">
                {{ formatDateTime(scope.row.auditDate) }}
            </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
                  <template slot-scope="scope">
                    <el-button
                      v-if="scope.row.auditStatus === '1'"
                      size="mini"
                      type="text"
                      @click="handleReconciliationUpdate(scope.row)"
                      :disabled="scope.row.recoStatus === '1'"
                      :class="{'disabled-button': scope.row.recoStatus === '1'}"
                    >
                      {{ scope.row.recoStatus === '1' ? '已对账' : '对账' }}
                    </el-button>
                  </template>
                </el-table-column>
        <el-table-column label="对账日期" width="180" align="center" prop="recoDate" />
        <el-table-column label="对账人" width="120" align="center" prop="recoName" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reconciliation, reconciliationParentDetail, reconciliationChildrenDetail, handleReconciliation, parentHandleReconciliation,auditReconciliation } from "@/api/mes/soa/reporeco";
import { getInfo  } from "@/api/login";

export default {
  name: 'Roporeco',
  data() {
    return {
      loading: true,
      childLoading: false,
      dialogVisible: false,
      queryParams: {
        status: 'CONFIRMED'
      },
      parentReconciliationData: [],
      childReconciliationList: [],
      currentParentRow: null,
       pageNum: 1,
          pageSize: 10,
          total: 0,
          childPageNum: 1,
          childPageSize: 10,
          childTotal: 0,
           currentUser: null // 存储当前登录用户信息
    };
  },
  created() {
    this.fetchParentReconciliationData();
     this.fetchCurrentUser(); // 获取当前登录用户信息
  },
  methods: {
      async fetchCurrentUser() {
        try {
          const response = await getInfo();
          console.log('后端返回的完整响应数据:', response); // 打印完整的响应数据

          if (response && response.data && response.data.user) {
            this.currentUser = response.data.user;
            console.log('当前用户信息:', this.currentUser);
          } else if (response && response.user) {
            this.currentUser = response.user; // 直接从 response 中获取用户信息
            console.log('当前用户信息:', this.currentUser);
          } else {
            console.error('获取当前用户信息失败：返回数据为空');
          }
        } catch (error) {
          console.error('获取当前用户信息失败:', error);
        }
      },


    // 数据同步
    async syncReconciliationData() {
      try {
        await reconciliation();
        this.$message.success('数据同步成功');
        this.fetchParentReconciliationData(); // 刷新列表
      } catch (error) {
        this.$message.error('数据同步失败');
        console.error('数据同步失败:', error);
      }
    },

    // 获取父节点数据
    async fetchParentReconciliationData() {
        try {
          this.loading = true;
          const response = await reconciliationParentDetail({
                  ...this.queryParams,
                  pageNum: this.pageNum,
                  pageSize: this.pageSize
                });
          this.parentReconciliationData = response.rows || [];
          this.total = response.total || 0;
          this.loading = false;
        } catch (error) {
          this.loading = false;
          this.$message.error('获取对账数据失败');
          console.error('获取父节点对账数据失败:', error);
        }
      },

    // 显示子节点对话框
    async showChildDialog(row) {
        try {
                this.dialogVisible = true;
                this.childLoading = true;
                this.currentParentRow = row;
                const storageId = String(row.storageId || row.serialNum);

                const response = await reconciliationChildrenDetail(
                    this.queryParams,
                    storageId
                );
                this.childReconciliationList = response.rows || [];
                this.childLoading = false;
                 // 更新父节点状态
                       this.updateParentReconciliationStatus(row);

            } catch (error) {
                this.childLoading = false;
                this.$message.error('获取子节点数据失败');
                console.error('获取子节点数据失败:', error);
            }
    },

      // 审核
      async auditReconciliationUpdate(row) {
        try {
          const response = await auditReconciliation(row); // 调用后端接口
          if (response.code === 200) { // 如果后端返回成功
            this.$message.success('审核成功');
            // 更新当前行状态
            row.auditStatus = '1';
            row.auditName = this.currentUser; // 使用当前用户信息更新
            row.auditDate = new Date().toISOString().slice(0, 19).replace('T', ' '); // 格式化日期
          } else {
            // 如果后端返回失败，提示错误信息
            this.$message.error('审核失败: ' + response.msg);
          }
        } catch (error) {
          // 捕获网络请求或其他异常
          this.$message.error('审核失败');
          console.error('审核失败:', error);
        }
      },


    // 处理对账操作
    async handleReconciliationUpdate(row) {
       // 检查是否已经审核通过
            if (row.auditStatus !== '1') {
              this.$message.warning('请先进行审核');
              return;
            }

      try {
        await handleReconciliation(row);
        this.$message.success('对账成功');
        // 更新当前行状态
        row.recoStatus = '1';

        // 检查所有子节点是否都已对账
        if (this.currentParentRow) {
          const allChildrenReconciled = this.childReconciliationList.every(child => child.recoStatus === '1');
          if (allChildrenReconciled) {
            this.currentParentRow.recoStatus = '1';
            // 刷新父节点数据
            await this.updateParentReconciliationStatusOnServer(this.currentParentRow);
          }
        }
      } catch (error) {
        this.$message.error('对账失败');
        console.error('对账失败:', error);
      }
    },
     // 更新父节点对账状态
      updateParentReconciliationStatus(parentRow) {
        const allChildrenReconciled = this.childReconciliationList.every(child => child.recoStatus === '1');
        if (allChildrenReconciled) {
          parentRow.recoStatus = '1'; // 已完成
        } else {
          parentRow.recoStatus = '0'; // 未完成
        }
      },
      // 调用更新父节点接口
        async updateParentReconciliationStatusOnServer(parentRow) {
          try {
            await parentHandleReconciliation(parentRow);
            this.$message.success('父节点对账状态修改成功');
          } catch (error) {
            this.$message.error('父节点对账状态修改失败');
            console.error('父节点对账状态修改失败:', error);
          }
        },
// 分页事件处理
  handleSizeChange(newSize) {
    this.pageSize = newSize;
    this.fetchParentReconciliationData();
  },
  handleCurrentChange(newPage) {
    this.pageNum = newPage;
    this.fetchParentReconciliationData();
  },

    // 格式化日期时间
    formatDateTime(value) {
      if (!value) return '';
      return new Date(value).toLocaleString();
    },

    // 处理对话框关闭
    handleClose() {
      this.dialogVisible = false;
      this.childReconciliationList = [];
      this.currentParentRow = null;
    }
  }
  };

</script>

<style scoped>
.dashboard-editor-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;
}

.disabled-button {
  color: #909399;
  cursor: not-allowed;
}

.el-button--text {
  padding: 0;
  height: auto;
  &.disabled-button {
    color: #909399;
  }
}
</style>
